package demo;

import demo.DiscardServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author: zlz
 * @date: 2021/9/12 14:43
 * @description:
 * @since: JDK1.8
 */
public class NettyDemo {
    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程组bossgroup和workgroup,含有子线程NioEventLoop的个数默认为cpu核数的两倍
        // bossGroup只是处理连接请求，真正和客户端的业务处理，会交给workGroup完成
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
        try {
            // 创建服务器端的启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 使用链式编程配置参数
            serverBootstrap.group(bossGroup, workGroup) //设置两个线程组
                    // 使用NioServerSocketChannel作为服务器通道的实现
                    .channel(NioServerSocketChannel.class)
                    // 初始化服务器连接队列大小，服务端处理客户端请求是顺序处理的，所以同一时间只能处理一个客户端连接请求
                    // 多个客户端同时来的时候，服务端不能处理的客户端连接请求放在队列中等待处理
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler((new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new DiscardServerHandler());
                        }
                    }))
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            System.out.println("netty server started");
            ChannelFuture cf = serverBootstrap.bind(9000).sync();
            // 对关闭通道进行监听
            cf.channel().closeFuture().sync();

        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
